package model

import (
	"ginBasic/app/common/lib"
	"ginBasic/global"
)

var RoleModel = new(Role)

type Role struct {
	Id          int    `form:"id" json:"id"`
	Title       string `form:"title" json:"title"`
	Description string `form:"description" json:"description"`
	Status      int    `form:"status" json:"status"`
	AddTime     int    `form:"addTime" json:"addTime"`
}

func (Role) TableName() string {
	return "role"
}

// 获取角色列表
func GetRoleList() []Role {
	roleList := []Role{}
	global.DB.Find(&roleList)
	return roleList
}

// 添加角色
func AddRole(title, desc string, status int) bool {

	role := Role{}
	role.Title = title
	role.Description = desc
	role.Status = status
	role.AddTime = int(lib.GetUnix())
	err := global.DB.Create(&role).Error
	if err != nil {
		return false
	}
	return true
}

// 编辑角色
func EditRole(req Role) bool {

	role := Role{Id: req.Id}
	global.DB.Find(&role)
	role.Title = req.Title
	role.Description = req.Description
	role.Status = req.Status
	err := global.DB.Save(&role).Error
	if err != nil {
		// TODO 保存到日志文件
		return false
	}
	return true
}

// 根据id获取角色详情
func GetRoleById(id int) Role {
	info := Role{}
	global.DB.Where("id=?", id).Find(&info)
	return info
}

func DeleteRole(ids []string) (bool, error) {

	res := global.DB.Delete(&Role{}, ids)
	if res.Error != nil {
		//记录删除报错的原因 TODO
		return false, res.Error
	}
	return true, nil
}

func UpdateRoleStatus(req Role) (bool, error) {
	role := Role{Id: req.Id}
	global.DB.Find(&role)
	role.Status = req.Status
	err := global.DB.Save(&role).Error
	if err != nil {
		// TODO 保存到日志文件
		return false, err
	}
	return true, nil
}
